package cn.chainco.cts.idaoImpl;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import cn.chainco.cts.idao.IExcRateDao;
import cn.chainco.cts.jdo.Currency;
import cn.chainco.cts.jdo.ExcRate;

@SuppressWarnings({"unchecked"})
public class ExcRateDaoImpl extends GenericHibernateDaoImpl<ExcRate, Long> implements IExcRateDao{
	/**
	 * 获取当天币种对人民币的汇率
	 */
	public ExcRate findByDateAndCurrency(final Date date, final Currency c){
		List<ExcRate> list = this.getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException, SQLException{
				Query query = session.createQuery("from ExcRate where effectiveDate = ? and currency = ?");
				query.setParameter(0, date);
				query.setParameter(1, c);
				return query.list();
			}
		});
		if(list.isEmpty()){
			return null;
		}else{
			return list.get(0);
		}
	}

	/**
	 * 得到所有币种对人民币的最新汇率
	 */
	public Map<Currency, Float> getAllCurrencyToRMB(){
		Map<Currency, Float> map = new HashMap<Currency, Float>();
		map.put(this.getHibernateTemplate().get(Currency.class, 1L), 100f);
		
		String sql = " select * from m68_excrate group by currencyId order by effectiveDate desc ";
		List<ExcRate> list = this.getSession().createSQLQuery(sql).addEntity(ExcRate.class).list();
		for(ExcRate rate: list){
			map.put(rate.getCurrency(), rate.getToRMB());
		}
		return map;
	}
}
